package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcw.library.imagepicker.ImagePicker;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.UpDynamicBean;
import com.zlx.module_base.base_api.res_data.UploadBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.StringUt;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.bean.PathBean;
import com.zlx.sharelive.utils.DecimalInputTextWatcher;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.GlideLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发布图文
 */
public class ImageTextAc extends BaseAc {

    @BindView(R.id.ll_money)
    LinearLayout ll_money;
    @BindView(R.id.rv_image)
    RecyclerView rv_image;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.et_text)
    EditText et_text;
    @BindView(R.id.iv_izFee)
    ImageView iv_izFee;
    @BindView(R.id.tv_text)
    TextView tv_text;
    @BindView(R.id.et_video_money)
    EditText et_video_money;

    private int mImageNumber = 0;
    private String izFee = "0"; //动态是否收费 0 免费 1 收费 ',
    private String type = "1";
    private String lat, lng, city;
    public ArrayList<String> imageList = new ArrayList<>();
    private List<PathBean> mImagePath = new ArrayList<>();
    private ArrayList<String> mImagePath2 = new ArrayList<>();
    private CommonRecyclerViewAdapter<PathBean> mImageAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_image_text;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setDynamic();
                    break;
            }

        }
    };

    /**
     * 发布文章图文
     */
    private void setDynamic() {
        UpDynamicBean upDynamicBean = new UpDynamicBean();
        upDynamicBean.setLat(lat);
        upDynamicBean.setLng(lng);
        upDynamicBean.setCity(city);
        upDynamicBean.setText(et_text.getText().toString().trim());
        upDynamicBean.setTitle(et_title.getText().toString().trim());
        for (int i = 0; i < mImagePath.size(); i++) {
            if (i == 0) {
                upDynamicBean.setThumb(mImagePath.get(i).getPath());
            } else if (i == 1) {
                upDynamicBean.setThumb2(mImagePath.get(i).getPath());
            } else if (i == 2) {
                upDynamicBean.setThumb3(mImagePath.get(i).getPath());
            } else if (i == 3) {
                upDynamicBean.setThumb4(mImagePath.get(i).getPath());
            } else if (i == 4) {
                upDynamicBean.setThumb5(mImagePath.get(i).getPath());
            } else if (i == 5) {
                upDynamicBean.setThumb6(mImagePath.get(i).getPath());
            } else if (i == 6) {
                upDynamicBean.setThumb7(mImagePath.get(i).getPath());
            } else if (i == 7) {
                upDynamicBean.setThumb8(mImagePath.get(i).getPath());
            } else if (i == 8) {
                upDynamicBean.setThumb9(mImagePath.get(i).getPath());
            }
        }
        upDynamicBean.setType(type);
        upDynamicBean.setIzFee(izFee);
        upDynamicBean.setMoney(et_video_money.getText().toString().trim());
        ApiUtil.getServiceApi().setDynamic(SPUtil.getToken(this), upDynamicBean).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                showSuccess();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            dialogSuccess();
                        } else {
                            Toast.makeText(ImageTextAc.this, data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    private void dialogSuccess() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(ImageTextAc.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(ImageTextAc.this, R.layout.dialog_success, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        TextView tv_continue = view.findViewById(R.id.tv_continue);
        tv_continue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //继续
                dialog.dismiss();
                lat = "";
                lng = "";
                city = "";
                izFee = "0";
                type = "1";
                et_text.setText("");
                et_title.setText("");
                et_video_money.setText("");
                tv_text.setText("");
                mImagePath.clear();
                mImagePath2.clear();
                mImageAdapter.notifyDataSetChanged();
                ll_money.setVisibility(View.GONE);
            }
        });

        TextView tv_black = view.findViewById(R.id.tv_black);
        tv_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回首页
                dialog.dismiss();
                finish();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    @Override
    public void initViews() {
        super.initViews();

        mImagePath.clear();
        mImagePath2.clear();
        mImagePath.add(new PathBean());
        initRecyclerView();
        moneyLimit();
    }


    /**
     * 初始化上传图片
     */
    private void initRecyclerView() {
        rv_image.setLayoutManager(new GridLayoutManager(this, 3));

        mImageAdapter = new CommonRecyclerViewAdapter<PathBean>(this, mImagePath) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, PathBean entity, int position) {
                ImageView iv_delete = holder.getView(R.id.iv_delete);

                if (!StringUt.isEmpty(entity.getPath())) {
                    GlideImgManager.glideLoaderFileAdd(ImageTextAc.this,
                            new File(entity.getPath()), holder.getView(R.id.iv_image), 1);
                    iv_delete.setVisibility(View.VISIBLE);
                } else {
                    iv_delete.setVisibility(View.GONE);
                    ((ImageView) holder.getView(R.id.iv_image)).setImageResource(R.mipmap.img_add_image);
                }

                iv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mImagePath.remove(position);
                        mImagePath2.remove(position);
                        if (mImagePath.size() == 8) {
                            if (!StringUt.isEmpty(mImagePath.get(mImagePath.size() - 1).getPath())) {
                                mImagePath.add(new PathBean());
                            }
                        }
                        imageList.clear();
                        mImagePath2.clear();
                        List<String> imageList = new ArrayList<>();
                        for (int i = 0; i < mImagePath.size(); i++) {
                            if (!StringUt.isEmpty(mImagePath.get(i).getPath())) {
                                mImagePath2.add(mImagePath.get(i).getPath());
                                imageList.add(mImagePath.get(i).getPath());
                            }
                        }
                        imageList.addAll(imageList);
                        if (null != mImageAdapter) {
                            mImageAdapter.notifyDataSetChanged();
                        }
                    }
                });

            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_add_image;
            }
        };

        rv_image.setAdapter(mImageAdapter);

        mImageAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                List<String> imageList = new ArrayList<>();
                imageList.clear();
                for (int i = 0; i < mImagePath.size(); i++) {
                    if (!StringUt.isEmpty(mImagePath.get(i).getPath())) {
                        imageList.add(mImagePath.get(i).getPath());
                    }
                }
                imageList.addAll(imageList);
                //添加
                setHead();
            }
        });
    }


    private void setHead() {
        ImagePicker.getInstance()
                .setTitle("标题")//设置标题
                .setImagePaths(mImagePath2)
                .showCamera(true)//设置是否显示拍照按钮
                .showImage(true)//设置是否展示图片
                .showVideo(false)//设置是否展示视频
                .setSingleType(true)//设置图片视频不能同时选择
                .setMaxCount(9)//设置最大选择图片数目(默认为1，单选)
                .setImageLoader(new GlideLoader())//设置自定义图片加载器
                .start(ImageTextAc.this, 30);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode      break;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 30:
                if (resultCode == RESULT_OK && data != null) {
                    mImagePath.clear();
                    mImagePath2.clear();
                    List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                    for (String path : imagePaths) {
                        PathBean pathBean = new PathBean();
                        pathBean.setPath(path);
                        mImagePath.add(pathBean);
                        mImagePath2.add(path);
                    }
                    if (mImagePath.size() != 9) {
                        mImagePath.add(new PathBean());
                    }
                    mImageAdapter.notifyDataSetChanged();
                }
                break;
        }
        if (resultCode == 20) {
            String name = data.getStringExtra("name");
            String address = data.getStringExtra("address");
            lat = data.getStringExtra("lat");
            lng = data.getStringExtra("lng");
            city = data.getStringExtra("city");
            tv_text.setText(name + address);
        }
    }

    @OnClick({R.id.iv_back, R.id.bt_post, R.id.ll_izFee, R.id.ll_address})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_post:
                if (StringUt.isEmpty(et_title.getText().toString().trim())) {
                    Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(et_text.getText().toString().trim()) &&
                        mImagePath.size() < 1) {
                    Toast.makeText(this, "请输入内容并选择图片", Toast.LENGTH_SHORT).show();
                    return;
                } else if (izFee.equals("0")) {
                    //免费
                    releasePosts();
                    return;
                } else if (izFee.equals("1")) {
                    //收费
                    if (StringUt.isEmpty(et_video_money.getText().toString().trim())) {
                        Toast.makeText(this, "请输入收费金额", Toast.LENGTH_SHORT).show();
                        return;
                    }  else if (
                            Double.valueOf(et_video_money.getText().toString().trim()) == 0) {
                        Toast.makeText(this, "请输入有效金额", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        //上传
                        releasePosts();
                    }
                }
                break;
            case R.id.ll_izFee:
                if (izFee.equals("1")) {
                    izFee = "0";
                    iv_izFee.setImageResource(R.mipmap.up_off_img);
                    ll_money.setVisibility(View.GONE);
                } else {
                    izFee = "1";
                    iv_izFee.setImageResource(R.mipmap.up_no_img);
                    ll_money.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.ll_address:
                startActivityForResult(new Intent(this, AddressListAc.class), 20);
                break;
        }

    }

    private void releasePosts() {
        if (mImagePath.size() > 0) {
            mImageNumber = 0;
            showLoading();
            for (int i = 0; i < mImagePath.size(); i++) {
                if (StringUt.isEmpty(mImagePath.get(i).getPath())) {
                    mImagePath.remove(i);
                }
            }
            if (mImagePath.size() > 0) {
                upImage();
            }
        }
    }

    private void upImage() {
        for (int i = 0; i < mImagePath.size(); i++) {
            mImagePath.get(i).setNumber(i);
        }
        AtomicInteger atomicInteger = new AtomicInteger();
        List<PathBean> mPathList = new ArrayList<>();
        for (int i = 0; i < mImagePath.size(); i++) {
            int finalI = i;
            List<File> mFile = new ArrayList<>();
            mFile.add(new File(mImagePath.get(i).getPath()));
            ApiUtil.getVideoApi().upload(filesToMultipartBody(mFile)).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UploadBean>>() {
                @Override
                public void onSuccess(ApiResponse<UploadBean> data) {
                    String img_url = data.getData().getInfo().get(0).getUrl();
                    ++mImageNumber;
                    atomicInteger.getAndIncrement();
                    PathBean pathBean = mImagePath.get(finalI);
                    pathBean.setPath(img_url);
                    mPathList.add(pathBean);
                    if (atomicInteger.get() >= mImagePath.size()) {
                        Collections.sort(mPathList, new Comparator<PathBean>() {
                            @Override
                            public int compare(PathBean o1, PathBean o2) {
                                return o1.getNumber() - o2.getNumber();
                            }
                        });
                        if (mImageNumber == (mImagePath.size())) {
                            mImagePath.clear();
                            mImagePath.addAll(mPathList);
                            //上传完成
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }
                }
            }));
        }
    }

    public static MultipartBody filesToMultipartBody(List<File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (File file : files) {
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            builder.addFormDataPart("file", file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    /**
     * 金钱限制
     */
    private void moneyLimit() {
        et_video_money.addTextChangedListener(new DecimalInputTextWatcher(et_video_money, 10, 2));
    }
}

